import asyncio
import datetime
import queue
import threading
from Common import Common


async def run_task(task_queue, task_function):
    while True:
        task = task_queue.get()
        if task is None:
            break
        try:
            # 直接调用协程函数
            await task_function(task)
        except Exception as e:
            print(f"{task_function}任务执行出错: {e}, {task}重新放回队列")
            task_queue.put(task)
        finally:
            task_queue.task_done()


def thread_function(task_queue, task_function):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(run_task(task_queue, task_function))
    loop.close()


def execute_async_task_concurrently(items, task_function):
    print(f"开始执行 {task_function.__name__} 任务" + str(datetime.datetime.now()))
    task_queue = queue.Queue()
    for item in items:
        task_queue.put(item)

    # 创建线程执行任务
    threads = []
    threads_num = min(task_queue.qsize(), Common.THREAD_COUNT)
    for _ in range(threads_num):
        t = threading.Thread(target=thread_function, args=(task_queue, task_function))
        t.start()
        threads.append(t)

    # 等待所有任务执行完成
    task_queue.join()

    # 停止线程
    for _ in range(threads_num):
        task_queue.put(None)
    for t in threads:
        t.join()
    print(f"{task_function.__name__} 任务执行完" + str(datetime.datetime.now()))
